package com.yuou.data.logscollection.server.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * 日志-切面
 * @author hpt
 * @since 2021/4/14.
 */
@Slf4j
public class AopLog {

    private static final String START_TIME = "request-start";

    private static final String REQUEST_ID = "request_id";

    private static final String STR_UNKNOWN = "unknown";

    /**
     * 切入点
     */
    @Pointcut("execution(public * com.yuou.data.logscollection.server.controller.*Controller.*(..))")
    public void log() {

    }

    /**
     * 前置操作
     *
     * @param point 切入点
     */
    @Before("log()")
    public void beforeLog(JoinPoint point) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        Map<String, String[]> parameterMap = request.getParameterMap();
        StringBuilder sb = new StringBuilder();
        String requestId = IdUtil.simpleUUID();
        sb.append("\n【request_id】：").append(requestId);
        sb.append("\n【请求 URL】：").append(request.getRequestURL());
        sb.append("\n【请求 IP】：").append(getIp(request));
        sb.append("\n【请求类名】：").append(point.getSignature().getDeclaringTypeName());
        sb.append("【请求方法名】：").append(point.getSignature().getName());
        sb.append("\n【body】：").append(JSONUtil.toJsonStr(point.getArgs()));
        sb.append("\n【请求参数】：").append(JSONUtil.toJsonStr(parameterMap));
        log.info(sb.toString());

        Long start = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
        request.setAttribute(REQUEST_ID, requestId);
    }

    /**
     * 环绕操作
     *
     * @param point 切入点
     * @return 原方法返回值
     * @throws Throwable 异常信息
     */
    @Around("log()")
    public Object aroundLog(ProceedingJoinPoint point) throws Throwable {
        Object result = point.proceed();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        String requestId = (String) request.getAttribute(REQUEST_ID);
        String sb = "\n【request_id】：" + requestId + "\n【返回值】：" + JSONUtil.toJsonStr(result);
        log.info(sb);
        return result;
    }

    /**
     * 后置操作
     */
    @AfterReturning("log()")
    public void afterReturning() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        String requestId = (String) request.getAttribute(REQUEST_ID);
        StringBuilder sb = new StringBuilder();
        sb.append("\n【request_id】：").append(requestId);
        Long start = (Long) request.getAttribute(START_TIME);
        Long end = System.currentTimeMillis();
        sb.append("\n【请求耗时】：").append((end - start)).append("毫秒");

        log.info(sb.toString());
    }

    /**
     * 获取请求ip
     * @param request
     * @return
     */
    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StrUtil.isBlank(ip) || STR_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || STR_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || STR_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
